package logic

import (
	"context"
	"errors"
	"gorm.io/gorm"
	"novel-kit/model/mysql"
	"strconv"

	"novel-kit/novelrpc/internal/svc"
	"novel-kit/novelrpc/novelrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type NovelAddLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewNovelAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *NovelAddLogic {
	return &NovelAddLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 小说添加
func (l *NovelAddLogic) NovelAdd(in *novelrpc.NovelAddRequest) (*novelrpc.NovelAddResponse, error) {
	// todo: add your logic here and delete this line
	var findUser mysql.User
	if err := findUser.FindUserById(mysql.DB, in.UserId); err != nil {
		return nil, errors.New("用户不存在")
	}

	novelAdd := mysql.Novel{
		Model:      gorm.Model{},
		NovelName:  in.NovelName,
		Content:    in.Content,
		NovelType:  in.NovelType,
		NovelImage: "https://cn.bing.com/images/search?q=%e5%b0%8f%e8%af%b4%e5%9b%be%e7%89%87&id=21929020CFE12CFC8DC0A0F64E7C445C5276BC5C&FORM=IACFIR",
		UserId:     int(in.UserId),
	}

	if novelAdd.NovelName == "" || novelAdd.NovelType == "" || novelAdd.Content == "" {
		return nil, errors.New("必填字段不能为空")
	}

	if err := novelAdd.NovelAdd(mysql.DB); err != nil {
		return nil, errors.New("添加失败")
	}
	return &novelrpc.NovelAddResponse{
		NovelId: strconv.Itoa(int(novelAdd.ID)),
	}, nil
}
